package com.jiutong.meipenggang.ui.activitys;


import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.jiutong.meipenggang.R;
import com.jiutong.meipenggang.base.AppManager;
import com.jiutong.meipenggang.base.BaseActivity;
import com.jiutong.meipenggang.base.CommonAdapter;
import com.jiutong.meipenggang.base.ViewHolder;
import com.jiutong.meipenggang.common.Constants;
import com.jiutong.meipenggang.entity.TotalMoneyDetailBean;
import com.jiutong.meipenggang.http.model.interfaces.TotalMoneyDetailBiz;
import com.jiutong.meipenggang.http.model.requests.TotalMoneyDetailRequest;
import com.jiutong.meipenggang.http.present.TotalMoneyDetailPresent;
import com.jiutong.meipenggang.http.subscribers.ProgressSubscriber;
import com.jiutong.meipenggang.http.subscribers.SubscriberOnNextListener;
import com.jiutong.meipenggang.utils.NumUilt;
import com.jiutong.meipenggang.utils.SpConfig;
import com.jiutong.meipenggang.utils.TimeUitl;
import com.jiutong.meipenggang.views.dialog.TimePickerDialog;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * @author Veken
 */
public class BillDetailActivity extends BaseActivity {


    @Bind(R.id.rl_common_title_back)
    RelativeLayout rlCommonTitleBack;
    @Bind(R.id.tv_common_title)
    TextView tvCommonTitle;
    //    @Bind(R.id.lv_bill_detail)
//    ListView lvBillDetail;
//    @Bind(R.id.tv_detail_item_time)
//    TextView tvDetailItemTime;
//    @Bind(R.id.tv_bill_detail_item_choice)
//    TextView tvBillDetailItemChoice;
    @Bind(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    @Bind(R.id.lv_total_money)
    ListView lvTotalMoney;
    @Bind(R.id.tv_detail_item_time)
    TextView tvDetailItemTime;
    @Bind(R.id.tv_bill_detail_item_choice)
    TextView tvBillDetailItemChoice;

    private TimePickerDialog timePickerDialog;
//    private MyExpandableListViewAdapter adapter;

    //    private Map<String, List<TotalMoneyDetailBean.ListBean>> dataset = new HashMap<>();
//    private String[] parentList;
//    private List<TotalMoneyDetailBean.ListBean> childrenList = new ArrayList<>();
    private List<TotalMoneyDetailBean.ListBean> list = new ArrayList<>();

    private int currentMonth;
    private int currentYear;
    private TotalMoneyDetailRequest request;
    private TotalMoneyAdapter adapter;
    private int currentPage = 1;
    private String time;

    @Override
    public int getLayoutResouceId() {
        return R.layout.activity_bill_detail;
    }

    @Override
    protected void initView() {
        super.initView();
        tvCommonTitle.setText("详情");

    }

    @Override
    protected void onResume() {
        super.onResume();
        //刷新
        tvDetailItemTime.setText(currentYear + "年" + currentMonth + "月");
        loadData();
        fresh();

    }

    /**
     * 初始化数据
     */
    private void loadData() {
        if (request == null) {
            request = new TotalMoneyDetailRequest();
        }
        SubscriberOnNextListener onNextListener = new SubscriberOnNextListener<TotalMoneyDetailBean>() {
            @Override
            public void onNext(TotalMoneyDetailBean o) {
                if(o.getError()==-1){
                    list = o.getList();
                    SpConfig.getInstance().edit().putString(Constants.ID, o.getId()).commit();
                    SpConfig.getInstance().edit().putString(Constants.TOKEN, o.getToken()).commit();
                    if(list.size()>0){
                        adapter = new TotalMoneyAdapter(BillDetailActivity.this, list, R.layout.child_item);
                        lvTotalMoney.setAdapter(adapter);

                    }else{
                        toastShortShow("没有数据");
                    }
                }else{
                    toastShortShow(o.getMsg());
                }
            }

            @Override
            public void onError(Throwable e) {

            }
        };
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("OPT", 23);
        hashMap.put("timestamp", TimeUitl.getDate());
        hashMap.put("id", SpConfig.getInstance().getString(Constants.ID));
        hashMap.put("token", SpConfig.getInstance().getString(Constants.TOKEN));
        hashMap.put("currPage", "1");
        hashMap.put("time", "");
        request.getTotalMoneyDetail(new ProgressSubscriber(onNextListener, mContext), hashMap);
    }

    /**
     * 下拉刷新，上拉加载
     */
    private void fresh() {
        ClassicsHeader classicsHeader = new ClassicsHeader(this);
        long currentTimeMillis = System.currentTimeMillis();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = new Date(currentTimeMillis);
        classicsHeader.setLastUpdateText("上次更新 "+sdf.format(date));
        refreshLayout.setRefreshHeader(classicsHeader);
        //设置 Footer 为 经典样式
        refreshLayout.setRefreshFooter(new ClassicsFooter(this));
        //刷新
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                loadMore("1", time);
                refreshlayout.finishRefresh(2000/*,false*/);//传入false表示刷新失败
            }
        });
        //加载更多
        refreshLayout.setOnLoadmoreListener(new OnLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                refreshlayout.finishLoadmore(1000/*,false*/);//传入false表示加载失败
                loadMore(++currentPage + "", "");
            }
        });
    }

    /**
     * 加载更多
     *
     * @param currPage
     */
    private void loadMore(String currPage, final String time) {
        if (request == null) {
            request = new TotalMoneyDetailRequest();
        }
        SubscriberOnNextListener onNextListener = new SubscriberOnNextListener<TotalMoneyDetailBean>() {
            @Override
            public void onNext(TotalMoneyDetailBean o) {
                if(o.getError()==-1){
                    SpConfig.getInstance().edit().putString(Constants.ID, o.getId()).commit();
                    SpConfig.getInstance().edit().putString(Constants.TOKEN, o.getToken()).commit();
                    showData(o);
                }else{
                    toastShortShow(o.getMsg());
                }
            }

            @Override
            public void onError(Throwable e) {

            }
        };
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("OPT", 23);
        hashMap.put("timestamp", TimeUitl.getDate());
        hashMap.put("id", SpConfig.getInstance().getString(Constants.ID));
        hashMap.put("token", SpConfig.getInstance().getString(Constants.TOKEN));
        hashMap.put("currPage", currPage);
        hashMap.put("time", time);
        request.getTotalMoneyDetail(new ProgressSubscriber(onNextListener, mContext), hashMap);
    }

    private void showData(TotalMoneyDetailBean bean) {
        if (bean.getList().size() > 0) {
            for (int i = 0; i < bean.getList().size(); i++) {
                list.add(bean.getList().get(i));
            }
        } else {
            toastShortShow("没有数据");
        }
        adapter.notifyDataSetChanged();

    }

    class TotalMoneyAdapter extends CommonAdapter<TotalMoneyDetailBean.ListBean> {

        public TotalMoneyAdapter(Context context, List<TotalMoneyDetailBean.ListBean> listDatas, int layoutId) {
            super(context, listDatas, layoutId);
        }

        @Override
        protected void fillData(ViewHolder holder, int position) {
            TextView tv_bill_detail_item_day = holder.getView(R.id.tv_bill_detail_item_day);
            String hour = listDatas.get(position).getTime();
            String[] split = hour.split(" ");
            tv_bill_detail_item_day.setText(split[0] + "");
            TextView tv_bill_detail_item_hour = holder.getView(R.id.tv_bill_detail_item_hour);
            tv_bill_detail_item_hour.setText(split[1] + "");
            ImageView iv_bill_detail_item = holder.getView(R.id.iv_bill_detail_item);
            TextView tv_bill_detail_item_money = holder.getView(R.id.tv_bill_detail_item_money);
            switch (listDatas.get(position).getType()) {
                case 1:
                    //收入
                    iv_bill_detail_item.setBackgroundResource(R.mipmap.icon_shouru);
                    tv_bill_detail_item_money.setText("+" + NumUilt.formatString(listDatas.get(position).getAmount() + ""));
                    break;
                case 2:
                    //支出
                    iv_bill_detail_item.setBackgroundResource(R.mipmap.icon_zhichu);
                    tv_bill_detail_item_money.setText("-" + NumUilt.formatString(listDatas.get(position).getAmount() + ""));
                    break;
                case 3:
                    //冻结
                    iv_bill_detail_item.setBackgroundResource(R.mipmap.icon_dongjie);
                    tv_bill_detail_item_money.setText("-" + NumUilt.formatString(listDatas.get(position).getAmount() + ""));
                    break;
                case 4:
                    //解冻
                    iv_bill_detail_item.setBackgroundResource(R.mipmap.icon_jiedong);
                    tv_bill_detail_item_money.setText("+" + NumUilt.formatString(listDatas.get(position).getAmount() + ""));
                    break;
            }
            TextView tv_bill_detail_item_describe = holder.getView(R.id.tv_bill_detail_item_describe);
            tv_bill_detail_item_describe.setText(listDatas.get(position).getSummary());
        }
    }


    @Override
    protected void initDate(Bundle savedInstanceState) {
        super.initDate(savedInstanceState);
        Calendar cal = Calendar.getInstance();
        currentMonth = cal.get(Calendar.MONTH) + 1;
        currentYear = cal.get(Calendar.YEAR);
    }

    @OnClick({R.id.rl_common_title_back, R.id.tv_bill_detail_item_choice})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.rl_common_title_back:
                AppManager.getAppManager().finishActivity(this);
                break;
            case R.id.tv_bill_detail_item_choice:
                showTimeDialog();
            default:
                break;
        }
    }

    /**
     * 显示筛选的dialog
     */
    private void showTimeDialog() {
        timePickerDialog = new TimePickerDialog();
        timePickerDialog.setOnDialogClickListener(new TimePickerDialog.OnDialogClickListener() {
            @Override
            public void onBtnClick(String year, String month, String data) {
                list.clear();
                time = year + "-" + month;
                loadMore("1",time);
                tvDetailItemTime.setText(year + "年" + month + "月");
//                childrenList.clear();
//                dataset.clear();
                //取消最近三个月
//                if (year.equals("最近三个月")) {
//                    parentList = new String[3];
//                    for (int i = 0; i < parentList.length; i++) {
//                        parentList[i] = currentYear + "年" + (currentMonth - i) + "月";
//                    }
////                    for (int i = 0; i < 6; i++) {
////                        childrenList.add("1");
////                    }
////                    for (int i = 0; i < parentList.length; i++) {
////                        dataset.put(parentList[i], childrenList);
////                    }
//                } else {
//                parentList = new String[1];
//                parentList[0] = year + "年" + month + "月";
//                if (year.equals((currentYear - 1) + "")) {
//                    for (int i = 0; i < parentList.length; i++) {
//                        dataset.put(parentList[i], null);
//                        toastShortShow("该月没有数据");
//                    }
//                } else {
//                    loadMore("1", year + "-" + month);
////                        for (int i = 0; i < 6; i++) {
////                            childrenList.add("1");
////                        }
////                        for (int i = 0; i < parentList.length; i++) {
////                            dataset.put(parentList[i], childrenList);
////                        }
//                }
//                for (int i = 0; i < parentList.length; i++) {
//                    adapter.refresh(expandablelistview, i);
//                }
//                Log.d("dataset", dataset.toString());
                timePickerDialog.dismiss();
            }
        });
        timePickerDialog.show(getSupportFragmentManager(), TAG);
    }

//    /**
//     * 显示数据
//     *
//     * @param bean
//     */
//    private void showData(TotalMoneyDetailBean bean, String time) {
//        List<TotalMoneyDetailBean.ListBean> list = bean.getList();
//        if (TextUtils.isEmpty(time)) {
//            parentList[0] = currentYear + "年" + currentMonth + "月";
//        } else {
//            parentList[0] = time;
//        }
//        childrenList = list;
//        dataset.put(parentList[0], childrenList);
//        for (int i = 0; i < dataset.size(); i++) {
//            expandablelistview.expandGroup(i);
//        }
//        adapter = new MyExpandableListViewAdapter();
//        expandablelistview.setAdapter(adapter);
////            for (int i = 0; i < currentMonth; i++) {
////                parentList[i] = currentYear + "年" + (currentMonth - i) + "月";
////            }
//        //只保留一个月
////            for (int i = 0; i < parentList.length; i++) {
////                dataset.put(parentList[i], childrenList);
////            }
//        expandablelistview.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
//            @Override
//            public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) {
//                return true;
//            }
//        });
//    }

//
//    private class MyExpandableListViewAdapter extends BaseExpandableListAdapter {
//        private Handler handler = new Handler() {
//            @Override
//            public void handleMessage(Message msg) {
//                //更新数据
//                notifyDataSetChanged();
//                super.handleMessage(msg);
//            }
//        };
//
//
//        /*供外界更新数据的方法*/
//        public void refresh(ExpandableListView expandableListView, int groupPosition) {
//            handler.sendMessage(new Message());
//            //必须重新伸缩之后才能更新数据
//            expandableListView.collapseGroup(groupPosition);
//            expandableListView.expandGroup(groupPosition);
//        }
//
//        //  获得某个父项的某个子项
//        @Override
//        public Object getChild(int parentPos, int childPos) {
//            return dataset.get(parentList[parentPos]).get(childPos);
//        }
//
//        //  获得父项的数量
//        @Override
//        public int getGroupCount() {
//            if (dataset == null) {
//                return 0;
//            }
//            return dataset.size();
//        }
//
//        //  获得某个父项的子项数目
//        @Override
//        public int getChildrenCount(int parentPos) {
//            if (dataset.get(parentList[parentPos]) == null) {
//                return 0;
//            }
//            return dataset.get(parentList[parentPos]).size();
//        }
//
//        //  获得某个父项
//        @Override
//        public Object getGroup(int parentPos) {
//            return dataset.get(parentList[parentPos]);
//
//        }
//
//        //  获得某个父项的id
//        @Override
//        public long getGroupId(int parentPos) {
//            return parentPos;
//        }
//
//        //  获得某个父项的某个子项的id
//        @Override
//        public long getChildId(int parentPos, int childPos) {
//            return childPos;
//        }
//
//        //  按函数的名字来理解应该是是否具有稳定的id，这个函数目前一直都是返回false，没有去改动过
//        @Override
//        public boolean hasStableIds() {
//            return false;
//        }
//
//        //  获得父项显示的view
//        @Override
//        public View getGroupView(int parentPos, boolean b, View view, ViewGroup viewGroup) {
//            if (view == null) {
//                LayoutInflater inflater = (LayoutInflater) BillDetailActivity
//                        .this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
//                view = inflater.inflate(R.layout.parent_item, null);
//            }
//            view.setTag(R.layout.parent_item, parentPos);
//            view.setTag(R.layout.child_item, -1);
//            TextView tv_time = (TextView) view.findViewById(R.id.tv_detail_item_time);
//            //当parenList.length==1的时候，要提防parentList[parentPos]数组下标越界，
//            // parentPos滑动的时候，有可能为1，所以当只有一条数据的时候，直接得到下标为0的值
//            if (parentList.length == 1) {
//                tv_time.setText(parentList[0]);
//            } else {
//                tv_time.setText(parentList[parentPos]);
//            }
////            Log.d("tv_time",parentList[parentPos]);
//            //是否添加item之间的空格
////            View view1 = view.findViewById(R.id.view_bg);
//            TextView tx_choice = (TextView) view.findViewById(R.id.tv_bill_detail_item_choice);
//            if (parentPos == 0) {
////                view1.setVisibility(View.GONE);
//                tx_choice.setVisibility(View.VISIBLE);
//                tx_choice.setText("筛选");
//                //筛选按钮时间弹出框
//                tx_choice.setOnClickListener(new View.OnClickListener() {
//                    @Override
//                    public void onClick(View v) {
//                        showTimeDialog();
//                    }
//                });
//            } else {
//                tx_choice.setVisibility(View.GONE);
////                view1.setVisibility(View.VISIBLE);
//            }
//            return view;
//        }
//
//        //  获得子项显示的view
//        @Override
//        public View getChildView(int parentPos, int childPos, boolean b, View view, ViewGroup viewGroup) {
//            if (view == null) {
//                LayoutInflater inflater = (LayoutInflater) BillDetailActivity
//                        .this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
//                view = inflater.inflate(R.layout.child_item, null);
//            }
//            view.setTag(R.layout.parent_item, parentPos);
//            view.setTag(R.layout.child_item, childPos);
//            TextView tv_bill_detail_item_day = (TextView) view.findViewById(R.id.tv_bill_detail_item_day);
//            String hour = childrenList.get(parentPos).getTime();
//            String[] split = hour.split(" ");
//            tv_bill_detail_item_day.setText(split[0]);
//            TextView tv_bill_detail_item_hour = (TextView) view.findViewById(R.id.tv_bill_detail_item_hour);
//            tv_bill_detail_item_hour.setText(split[1]);
//            ImageView iv_bill_detail_item = (ImageView) view.findViewById(R.id.iv_bill_detail_item);
//            switch (childrenList.get(parentPos).getType()) {
//                case 1:
//                    //收入
//                    iv_bill_detail_item.setBackgroundResource(R.mipmap.icon_in);
//                    break;
//                case 2:
//                    //支出
//                    iv_bill_detail_item.setBackgroundResource(R.mipmap.icon_out);
//                    break;
//            }
//            TextView tv_bill_detail_item_money = (TextView) view.findViewById(R.id.tv_bill_detail_item_money);
//            tv_bill_detail_item_money.setText(childrenList.get(parentPos).getAmount());
//            TextView tv_bill_detail_item_describe = (TextView) view.findViewById(R.id.tv_bill_detail_item_describe);
//            tv_bill_detail_item_describe.setText(childrenList.get(parentPos).getSummary());
//            return view;
//        }
//
//        //  子项是否可选中，如果需要设置子项的点击事件，需要返回true
//        @Override
//        public boolean isChildSelectable(int i, int i1) {
//            return true;
//        }
//    }
}
